import router from "@/router";
import { useUserStoreHook } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";

import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { useAppStoreHook } from '@/store/modules/app';
NProgress.configure({ showSpinner: false }); // 进度条

const permissionStore = usePermissionStoreHook();
const useAppStore = useAppStoreHook();
const userStore = useUserStoreHook();

// 白名单路由
const whiteList = ["/login", '/404', '/401'];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const abpConfig = await useAppStore.applicationConfiguration();
  //console.log('abpConfig',abpConfig)
  //console.log('route', router.getRoutes());

  if (abpConfig.currentUser.isAuthenticated) {
    if (to.path === "/login") {
      // 如果已登录，跳转首页
      next({ path: "/", replace: true });
      NProgress.done();

    } else {
      const userName = userStore.userName;
      // debugger
      if (userName) {
         console.log('hasUserName',userName)
        if (to.matched.length === 0) {
          from.name ? next({ name: from.name }) : next("/404");
        } else {
          next();
        }
      } else {
        try {
          const userInfo = await userStore.getInfo()

          let roles = abpConfig.currentUser.roles;
          roles.forEach(role => {
            userStore.roles.push(role)
          })

          const grantedPolicies = abpConfig.auth.grantedPolicies as string[]
          const accessRoutes = await permissionStore.generateRoutes(
            grantedPolicies
          )
          accessRoutes.forEach((route) => {
            router.addRoute(route);
          });
          next({ ...to, replace: true })
          NProgress.done();
        } catch (error) {

        }
      }
    }
  } else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
